/*
 * @Author: your name
 * @Date: 2021-10-03 20:52:54
 * @LastEditTime: 2021-10-06 15:59:58
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bigdatavue\src\ntils\useWallmark.ts
 */
// 网站水印
import { unref, ref, computed } from 'vue'
import type { Ref } from 'vue'
import { nodebug } from './useDebug'
/**
 * @description: 
 * @param {*}
 * @return {*} 将变量定义到外围的主要的目的就是资源共享，利用缓存的原理，可以多个页面同时水印的显示，隐藏，更改等操作
 */
// 创建画布实例
let markEle:any
// 文字
let text:string | undefined = 'iFlow'
let markStatus = ref<Boolean>(false)
export class Wallmark {
    private appEle:any // 容器

    constructor(appEl:Ref<HTMLElement | null> = ref(document.body) as Ref<HTMLElement>) {
        this.appEle = unref(appEl)
    }

    // 创建画布并转化为base64格式渲染   
    createWorkMark = (str) => {
        const can = document.createElement('canvas')
        const width = 300
        const height = 200
        Object.assign(can, { width, height })
        const cans = can.getContext('2d')
        if (cans) {
            cans.rotate((-20 * Math.PI) / 120)
            cans.font = '15px Vedana'
            cans.fillStyle = 'rgba(0, 0, 0, 0.15)'
            cans.textAlign = 'left'
            cans.textBaseline = 'middle'
            cans.fillText(str, width / 20, height)
        }
        return can.toDataURL('image/png')
    }

    // 更新画布 更新也会触发创建
    updatewallmark = (options: {
        width?: string;
        height?: string;
        str?: string;
        } = {}) => {
        // 实例检测 
       
        if (!unref(markEle)) {
            this.createDiv(options.str)
            return false
        }
        // 字符串检测
        text = options.str 
        const el = unref(markEle)
        el.style.width = options.width
        el.style.height = options.height
        el.style.background = `url(${this.createWorkMark(options.str)}) left top repeat`
    }
     
    // 创建画板容器   
    async createDiv(str) {  
        markStatus.value = true
        let ParDiv = unref(this.appEle)
        if (unref(markEle)) return
        let oDiv = document.createElement('div')
        markEle = oDiv
        oDiv.id = Symbol('watermark-dom').toString() // 将实例id为枚举类型
        oDiv.className = 'watermark'
        oDiv.style.pointerEvents = 'none'
        oDiv.style.top = '0px'
        oDiv.style.left = '0px'
        oDiv.style.position = 'absolute'
        oDiv.style.zIndex = '100000'
        this.updatewallmark({ str, height: '100%', width: '100%' })
        ParDiv.appendChild(oDiv)
        // 开启水印之后自动开启反调试，用户打开控制台页面将会做出调整并且不能操作
        nodebug()
    }

    // 清除画布
    clearWallmark() {
        const el = unref(markEle)
        let ParDiv = unref(this.appEle)
        if (!el) return
        markEle = undefined
        markStatus.value = false
        el && ParDiv.removeChild(el)
    }
}

export const getMarkStatus = () => computed(() => unref(markStatus))